using System;
using Microsoft.SPOT;
using System.Collections;

namespace mfRCF.Core.Extensions
{
    public static class mfStringExtensions
    {

        static char[] C_STR_URL_START_PARAMETER_PLITTER = { '?' };
        static char[] C_STR_URL_PARAMETER_PLITTER = { '&' };
        static char[] C_STR_URL_INTERN_PARAMETER_PLITTER = { '=' };

        /// <summary>
        /// extracts url-paratmeter in the specified string
        /// </summary>
        /// <remarks>e.g.: 'rss?name=asdf&date=01.01.2014'</remarks>
        /// <param name="urlString">url string to parse</param>
        /// <returns>a hashtable, which contains all parsed parameters</returns>
        public static Hashtable ExtractUrlParameter(this string urlString)
        {
            try
            {
                var urlFirstSplit = urlString.Split(C_STR_URL_START_PARAMETER_PLITTER, 2);

                var parameterString = urlFirstSplit[1].Split(C_STR_URL_PARAMETER_PLITTER);

                var hashTable = new Hashtable(parameterString.Length);

                String[] parameterArr = new String[2];
                foreach (String parameter in parameterString)
                {
                    parameterArr = parameter.Split(C_STR_URL_INTERN_PARAMETER_PLITTER, 2);
                    hashTable.Add(parameterArr[0], parameterArr[1]);
                }

                return hashTable;
            }
            catch (Exception ex)
            {
                throw new mfRcfException("Error in 'ExtractUrlParameter' 4 '" + urlString + "'", ex);
            }
        }

        /// <summary>
        /// extracts the base url (without parameters)
        /// </summary>
        /// <param name="urlString">complete request ulr</param>
        /// <returns>base url</returns>
        public static string ExtractBaseUrl(this string urlString)
        {
            try
            {
                var urlFirstSplit = urlString.Split(C_STR_URL_START_PARAMETER_PLITTER, 2);

                var baseUrl = urlFirstSplit[0];

                return baseUrl.RemoveLastSlash();
            }
            catch (Exception ex)
            {
                throw new mfRcfException("Error in 'ExtractBaseUrl' 4 '" + urlString + "'", ex);
            }
        }

        /// <summary>
        /// removes the last slash '/' in specified string, if there is any
        /// </summary>
        /// <param name="value">the string</param>
        /// <returns>string without last slash</returns>
        public static string RemoveLastSlash(this string value)
        {
            if (value.Length > 0)
            {
                //remov
                if (value[value.Length - 1] == '/')
                {
                    value = value.Substring(0, value.Length - 1);
                }
                return value;
            }
            return value;
        }
    }
}
